import { Layout, Menu } from 'antd';
import React, { useState, useTransition } from 'react';
import {
  PieChartOutlined,
  DashboardOutlined,
  SnippetsOutlined,
  TagsOutlined,
  UserOutlined,
  ProductOutlined,
  QrcodeOutlined,
} from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { useLocation, useNavigate } from 'react-router-dom';

type MenuItem = Required<MenuProps>['items'][number];

function getItem(
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[],
  type?: 'group',
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
    type,
  } as MenuItem;
}
const routerTree: CustomRouteObject[] = [
  {
    path: '/',
    title: '首页',
    icon: <DashboardOutlined />,
  },
  {
    path: '/article',
    title: '文章管理',
    icon: <SnippetsOutlined />,
  },
  {
    path: '/tag',
    title: '标签',
    icon: <TagsOutlined />,
  },
  {
    path: '/type',
    title: '类型',
    icon: <TagsOutlined />,
  },
  {
    path: '/user',
    title: '用户',
    icon: <UserOutlined />,
  },
  {
    path: '/system',
    title: '系统管理',
    icon: <QrcodeOutlined />,
    children: [
      {
        path: '/system/info',
        title: '系统基本信息',
        icon: <ProductOutlined />,
      },
      {
        path: '/system/logs',
        title: '日志信息记录',
        icon: <PieChartOutlined />,
      },
    ],
  },
];
function formatMenu(routrs: CustomRouteObject[]) {
  const items: MenuItem[] = [];
  routrs.forEach((item) => {
    const icon = item.icon ? item.icon : <PieChartOutlined />;
    if (item.children && item.children.length) {
      items.push(getItem(item.title, item.path, icon, formatMenu(item.children)));
    } else {
      items.push(getItem(item.title, item.path, icon));
    }
  });
  return items;
}

export default function LayoutSider() {
  const [collapsed] = useState(false);
  const navigate = useNavigate();
  const menuTree = formatMenu(routerTree);
  const location = useLocation();

  const [isPending, startTransition] = useTransition();
  const currentPath = location.pathname;

  const handleClickMenu: MenuProps['onClick'] = ({ item, key, keyPath }) => {
    console.log(item, key, keyPath);
    startTransition(() => {
      console.log(isPending);
      navigate(key);
    });
  };
  return (
    <Layout.Sider>
      <Menu
        defaultSelectedKeys={[currentPath]}
        defaultOpenKeys={[currentPath]}
        mode="inline"
        theme="dark"
        inlineCollapsed={collapsed}
        items={menuTree}
        onClick={handleClickMenu}
      />
    </Layout.Sider>
  );
}
